package org.jash.demo2205.shop

import org.jash.demo2205.BR
import org.jash.demo2205.R
import org.jash.demo2205.databinding.FragmentCategoryBinding
import org.jash.demo2205.entity.Category
import org.jash.demo2205.entity.Goods
import org.jash.demo2205.mvvm.BaseFragment
import org.jash.demo2205.utils.CommonAdapter
import org.jash.demo2205.utils.Event


class CategoryFragment : BaseFragment<FragmentCategoryBinding, CategoryViewModel>() {
    lateinit var categoryAdapter:CommonAdapter<Category>
    lateinit var subcategoryAdapter:CommonAdapter<Category>
    lateinit var goodsAdapter: CommonAdapter<Goods>
    private var cid:Int = 0
    private var page:Int = 1
    private val size:Int = 10
    override fun initData() {
        categoryAdapter = CommonAdapter({ R.layout.item_category to BR.category })
        subcategoryAdapter = CommonAdapter({ R.layout.item_subcategory to BR.sub })
        goodsAdapter = CommonAdapter({ R.layout.item_goods to BR.goods})
        viewModel.categoriesLiveData.observe(viewLifecycleOwner) {
            categoryAdapter.clear()
            categoryAdapter += it
            showSubcategory(it[0].data ?: listOf())
        }
        viewModel.goodsLiveData.observe(viewLifecycleOwner) {
            if (page == 1) {
                goodsAdapter.clear()
            }
            goodsAdapter += it
            binding.refresh.closeHeaderOrFooter()
        }
        viewModel.getCategories()
    }

    override fun initView() {
        binding.category.adapter = categoryAdapter
        binding.subcategory.adapter = subcategoryAdapter
        binding.goods.adapter = goodsAdapter
        binding.refresh.setOnRefreshListener {
            page = 1
            viewModel.getGoods(cid, page, size)
        }
        binding.refresh.setOnLoadMoreListener {
            viewModel.getGoods(cid, ++page, size)
        }
    }

    override fun error(throwable: Throwable) {
        super.error(throwable)
        binding.refresh.closeHeaderOrFooter()
    }
    @Event("展示子分类")
    fun showSubcategory(data:List<Category>) {
        subcategoryAdapter.clear()
        subcategoryAdapter += data
        goodsAdapter.clear()
        if (data.isNotEmpty()) {
            showGoods(data[0].id)
        }
    }
    @Event("展示商品")
    fun showGoods(id:Int) {
        cid = id
        page = 1
        viewModel.getGoods(cid, page, size)
    }
}